<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/6
 * Time: 18:56
 */
namespace haibao\jiepai\common;

class App{

    /**
     * 比较两个版本号大小，新版本号比旧版本号大则返回true，否则返回false
     * @param $oldVersion
     * @param $newVersion
     * @return bool
     */
    public static function compareAppVersion($oldVersion, $newVersion)
    {
        if (!$oldVersion) {
            $oldVersion = '4.3.0';
        }
        $oldVar = explode('.', $oldVersion);
        $newVar = explode('.', $newVersion);

        array_map('intval', $oldVar, $newVar);

        $oldVersionCode = ($oldVar[0] ? $oldVar[0] : 0) * 1000000 + ($oldVar[1] ? $oldVar[1] : 0) * 1000 + ($oldVar[2] ? $oldVar[2] : 0) * 1;
        $newVersionCode = ($newVar[0] ? $newVar[0] : 0) * 1000000 + ($newVar[1] ? $newVar[1] : 0) * 1000 + ($newVar[2] ? $newVar[2] : 0) * 1;
        return ($newVersionCode > $oldVersionCode) ? true : false;
    }

    /**
     * 根据用户ID获取用户头像地址
     */
    public static function getAvatarUrl($userId, $size = 'big', $type = '')
    {
        $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'big';
        $userId = abs(intval($userId));
        $userId = sprintf("%09d", $userId);
        $dir1 = substr($userId, 0, 3);
        $dir2 = substr($userId, 3, 2);
        $dir3 = substr($userId, 5, 2);
        $typeadd = $type == 'real' ? '_real' : '';
        $avatarUrl = \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::CDN_URL_AVATAR) . $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($userId, -2) . $typeadd . "_avatar_$size.jpg";
        if (strpos(file_get_contents($avatarUrl), '<html>') !== false) {
            $avatarUrl = 'http://bbs.haibao.com/uc_server/images/noavatar_middle.gif';
        }
        return $avatarUrl;
    }

    /**
     * 解析APP接口结果参数
     */
    public static function parseAppResult(&$param, $filterKey = array()){

        if(is_array($param)){
            foreach($param as $key=>&$item){
                if(is_string($key) && in_array($key, $filterKey)) continue;
                if(is_array($item)) self::parseAppResult($item, $filterKey);
                if(is_string($item) && preg_match('/^(\d+)$/', $item)){
                    $param[$key] = intval($item);
                }
            }
        }

        return $param;
    }
}